package com.atguigu.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class demo5 {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入您想要查找的路径");
        File root=new File(scanner.next());
        System.out.println("请输入要查询的关键字");
        String dest=scanner.next();
        //扫描目录
        Scandir(root,dest);
    }

    private static void Scandir(File root, String dest) throws IOException {
        File[] files=root.listFiles();
        if(files==null){
            return;
        }
        for(File f:files){
            if(f.isDirectory()){
                Scandir(f,dest);
            }else{
                check(f,dest);
            }
        }
    }

    private static void check(File f, String dest) throws IOException {
        if(f.getName().contains(dest)){
            System.out.println(f.getCanonicalPath()+"文件名中包含关键字"+dest);
        }
        try(InputStream inputStream=new FileInputStream(f)){
            StringBuilder stringBuilder=new StringBuilder();
            Scanner scanner=new Scanner(inputStream);
            while(scanner.hasNextLine()){
                stringBuilder.append(scanner.nextLine()+"\n");
            }
            if(stringBuilder.toString().contains(dest)){
                System.out.println(f.getCanonicalPath()+"文件内容包含"+dest);
            }
        }
    }
}
